package com.lcc.lynx.base.system.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import com.lcc.lynx.common.ResultVO;
import com.lcc.lynx.common.utils.CheckUtil;
import com.lcc.lynx.common.utils.RsaUtil;
import com.lcc.lynx.common.utils.StrUtil;
import com.lcc.lynx.jdbc.IByIdController;
import com.lcc.lynx.security.annotation.Permission;
import com.lcc.lynx.base.system.pojo.dv.SysUserDV;
import com.lcc.lynx.base.system.service.SysUserService;
import com.lcc.lynx.security.annotation.RepeatSubmit;
import com.lcc.lynx.security.config.SecurityProperties;
import com.lcc.lynx.base.system.util.FTPUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 系统用户控制实现
 * @auth lcc
 * @date 2024-12-30
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sys/user")
public class SysUserController implements IByIdController<SysUserDV> {

    private SysUserService service;
    private SecurityProperties securityProperties;


    @Override
    public SysUserService getService() {
       return service;
    }


    @RequestMapping("/addAndRole")
    @Permission(Permission.add)
    @RepeatSubmit
    public ResultVO addAndRole(@RequestBody SysUserDV dv){
        service.addAndRole(dv);
        return ResultVO.success();
    }

    @RequestMapping("/updateAndRole")
    @Permission(Permission.upd)
    public ResultVO updateAndRole(@RequestBody SysUserDV dv){
        service.updateAndRole(dv);
        return ResultVO.success();
    }

    @RequestMapping("/updatePwd")
    @Permission(Permission.upd)
    public ResultVO updatePwd(SysUserDV dv){
        String errorMsg = CheckUtil.of(dv)
                .check(dv::getUserId, "用户id")
                .check(dv::getOldPassword, "旧密码")
                .check(dv::getNewPassword, "新密码")
                .getErrorMsg();
        if(errorMsg != null){
            return ResultVO.fail(errorMsg);
        }

        SysUserDV user = service.selectById(dv.getUserId());
        String oldPwd = RsaUtil.decrypt(dv.getOldPassword(), KeyType.PrivateKey);
        String md5OldPwd = SecureUtil.hmacMd5(securityProperties.getMd5Key()).digestHex(oldPwd);
        if(!user.getPassword().equals(md5OldPwd)){
            return ResultVO.fail("原密码错误");
        }
        String newPwd = RsaUtil.decrypt(dv.getNewPassword(), KeyType.PrivateKey);
        String regex = securityProperties.getPasswordRegex();
        if(StrUtil.isNotEmpty(regex) && !newPwd.matches(regex)){
            return ResultVO.fail(securityProperties.getPasswordRegexMsg());
        }
        String md5NewPwd = SecureUtil.hmacMd5(securityProperties.getMd5Key()).digestHex(newPwd);
        SysUserDV update = new SysUserDV();
        update.setUserId(dv.getUserId());
        update.setPassword(md5NewPwd);
        service.updateById(update);
        return ResultVO.success();
    }

    @RequestMapping("/resetPwd")
    @Permission(Permission.upd)
    public ResultVO resetPwd(SysUserDV dv){
        String errorMsg = CheckUtil.of(dv)
                .check(dv::getUserId, "用户id")
                .getErrorMsg();
        if(errorMsg != null){
            return ResultVO.fail(errorMsg);
        }
        String md5NewPwd = SecureUtil.hmacMd5(securityProperties.getMd5Key()).digestHex(securityProperties.getDefaultPassword());
        SysUserDV update = new SysUserDV();
        update.setUserId(dv.getUserId());
        update.setPassword(md5NewPwd);
        service.updateById(update);
        return ResultVO.success();
    }

    @RequestMapping("/uploadPicture")
    @Permission(Permission.upload)
    public ResultVO uploadPicture(@RequestParam("file") MultipartFile file) throws IOException {
        UUID uuid = UUID.randomUUID();
        String userHeaderImgUrl = "http://121.199.69.177/static/user/picture/";
        String filename = file.getOriginalFilename();
        int i = filename.lastIndexOf(".");
        if(i < 0){
            return ResultVO.error("文件名不合法");
        }
        List<String> suffixes = Arrays.asList(".png", ".jpg");
        String suffix = filename.substring(i);
        if(!suffixes.contains(suffix)){
            return ResultVO.error("文件格式不合法,只允许png和jpg");
        }
        String fileName = uuid.toString().replace("-", "") + filename.substring(i);

        // 如果是linux 系统
        if(System.getProperty("os.name").toLowerCase().contains("linux")){
//            直接保存文件
            file.transferTo(new File("/www/wwwroot/static/user/picture/" + fileName));
            return ResultVO.success(userHeaderImgUrl + fileName);
        }

        File localFile = null;
        try{
            // 保存上传的文件到本地
            localFile = new File(FTPUtil.LOCAL_DIRECTORY);
            if(!localFile.exists()){
                localFile.mkdirs();
            }
            localFile = new File(localFile , fileName);
            file.transferTo(localFile);
            // 使用FTP工具类上传文件到远程服务器
            if(FTPUtil.uploadFile(localFile.getPath(), "/user/picture")){
                return ResultVO.success(userHeaderImgUrl + fileName);
            }
        }catch (Exception e){
            System.out.println("上传失败" + e.getMessage());
        }finally {
            if(localFile != null){
                // 删除本地文件
                localFile.delete();
            }
        }

        return ResultVO.error("上传失败");
    }


}